import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_drag_scale_widget/flutter_drag_scale_widget.dart';
import 'package:flutter_learn_vi/src/bean/bean_ppt_course.dart';
import 'package:flutter_learn_vi/src/bean/bean_video.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/page/study/course/video_progress_request_model.dart';
import 'package:get/get.dart';
import 'package:wakelock/wakelock.dart';

import '../../../bean/bean_integral.dart';
import '../../../bean/bean_train.dart';
import '../../../bean/bean_video_course.dart';
import '../../../common/user_helper.dart';
import '../../../utils/log_util.dart';
import '../controller/video_details_ppt_controller.dart';
import 'course_http_model.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2/28/21.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
///PPT页面
class PPTDetailsPage extends StatefulWidget {
  final VideoModel videoModel;
  final int trainId;
  final TrainBean trainBean;
  final IntegralStatBean integralStatBean;

  const PPTDetailsPage({
    Key key,
    @required this.videoModel,
    this.trainId,
    this.integralStatBean,
    this.trainBean,
  }) : super(key: key);

  @override
  _PPTDetailsPageState createState() => _PPTDetailsPageState();
}

class _PPTDetailsPageState extends State<PPTDetailsPage>
    with CourseHttpModel, VideoProgressRequestModel, WidgetsBindingObserver {
  VideoDetailsPPtController _videoDetailsPPtController;

  @override
  void initState() {
    super.initState();
    //使用
    Wakelock.enable();
    _getCourseVideoList();
    _videoDetailsPPtController = Get.put(
        VideoDetailsPPtController(
          widget.videoModel,
          widget.integralStatBean,
          widget.trainId,
          widget.trainBean,
        ),
        tag: widget.videoModel.id.toString());
    _videoDetailsPPtController.closeLoading = false;
    //缓存的人脸识别记录时间
    _videoDetailsPPtController.faceRecognitionNumber =
        UserHelper.getInstance.faceRecognitionNumber;
    Future.delayed(Duration.zero, () {
      _videoDetailsPPtController.initFunction();
    });
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      // 应用进入前台
      LogUtils.e("App进入 前台");
    } else if (state == AppLifecycleState.paused) {
      // 应用进入后台
      LogUtils.e("应用进入后台");
      _videoDetailsPPtController.stopAllFunction();
      Get.back();
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        _videoDetailsPPtController.closePage();
        return true;
      },
      child: GetBuilder(
        id: "root",
        tag: widget.videoModel.id.toString(),
        builder: (VideoDetailsPPtController controller) {
          return Scaffold(
            appBar: AppBar(
              leading: BackButton(
                onPressed: () {
                  _videoDetailsPPtController.closePage();
                },
              ),
              title: Text("课件详情"),
              actions: [
                buildProgressSlider(),
              ],
            ),
            body: Stack(
              children: [
                Container(
                  padding: EdgeInsets.all(20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "当前课程：${widget.videoModel.videoName}",
                        style: TextStyle(color: Colors.blueGrey),
                      ),
                      Divider(),
                      Text(
                        "1、可双指放大查看",
                        style: TextStyle(color: Colors.blueGrey),
                      ),
                      Text(
                        "2、可左右滑动查看",
                        style: TextStyle(color: Colors.blueGrey),
                      ),
                    ],
                  ),
                ),
                buildMain(),
                buildCloseLoading(controller),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget buildCloseLoading(VideoDetailsPPtController controller) {
    if (!controller.closeLoading) {
      return SizedBox(
        width: 1,
        height: 1,
      );
    }
    return Container(
      color: Colors.white.withOpacity(0.6),
      child: Center(
        child: CupertinoActivityIndicator(),
      ),
    );
  }

  Widget buildMain() {
    if (_isLoading) {
      return LoadingWidget();
    }

    if (_list.length == 0) {
      return Center(
        child: NoDataWidget(
          clickCallBack: () {
            setState(() {
              _isLoading = true;
            });
            _getCourseVideoList();
          },
        ),
      );
    }

    return ImageShowPageView(
      useCache: true,
      //图片数据
      imageList: _imageList,
      //图片的类型
      imageShowType: ImageShowType.NET,
      //图片的填充方式
      boxFit: BoxFit.contain,
      onPageChanged: (int index) {
        _updateStudy(index);
      },
    );
  }

  buildProgressSlider() {
    return GetBuilder(
      id: "progress",
      tag: widget.videoModel.id.toString(),
      builder: (VideoDetailsPPtController controller) {
        bool loadingUserStudy = controller.loadingUserStudy;
        if (loadingUserStudy) {
          return LoadingWidget();
        }
        UserStudyCourseBean userStudyCourseBean =
            controller.userStudyCourseBean;
        if (userStudyCourseBean != null) {
          int studyFinish = userStudyCourseBean.studyFinish;
          if (studyFinish == 1) {
            return Container(
              child: Row(
                children: [
                  // Image.asset(
                  //   "assets/images/2.0x/finish_icon.png",
                  //   width: 22,
                  //   height: 22,
                  // ),

                  Text(
                    "已完成学习",
                    style: TextStyle(color: Colors.green),
                  ),
                  SizedBox(width: 12),
                ],
              ),
            );
          }
        }
        return Container(
          width: 30,
          height: 30,
          margin: EdgeInsets.only(right: 12),
          child: Stack(
            alignment: Alignment.center,
            children: [
              SizedBox(
                width: 10,
              ),
              SizedBox(
                width: 30,
                height: 30,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  value: controller.getCurrentProgressValue(),
                  backgroundColor: Colors.grey.withOpacity(0.5),
                  valueColor: new AlwaysStoppedAnimation<Color>(Colors.green),
                ),
              ),
              Text(
                controller.getCurrentProgressStr(),
                style: TextStyle(
                  fontSize: 10,
                  color: Colors.green,
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  List<BeanPptCourse> _list = [];
  List<String> _imageList = [];
  bool _isLoading = true;

  ///获取课程视频详情
  void _getCourseVideoList() async {
    _list = await getPptList(videolevelId: widget.videoModel.id);
    _isLoading = false;
    _imageList = [];
    _list.forEach((element) {
      _imageList.add(element.pptImage);
    });
    if (_imageList.length > 0) {
      _updateStudy(1);
    }
    if (mounted) {
      setState(() {});
    }
  }

  void _updateStudy(int index) {
    updateVideo(
        trainId: widget.trainId,
        videoId: widget.videoModel.id,
        videoCourseId: widget.videoModel.videoCourseId,
        current: index,
        total: _imageList.length);
  }

  @override
  void dispose() {
    //不在使用
    Wakelock.disable();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
}
